﻿using System;
using System.Collections.Generic;
using System.Linq;
using Zero.Data.Repositories;
using System.Configuration;
using Zero.Entity.Models;
using Zero.Core.Extensions;
using Zero.Core;
using Zero.Data.Infrastructure;

namespace Zero.Service
{
    public class SystemService  : ISystemService
    {
        public readonly IUnitOfWork unitOfWork;
        public readonly IUserRepository userRepository;
        public readonly IMenuRepository menuRepository;

        //注意这里是读取配置文件，你也可以改成读取数据库等其他方式
        public  string AdminUserID = ConfigurationManager.AppSettings["AdminUserID"].ToStr();
        public  string AdminRoleID = ConfigurationManager.AppSettings["AdminRoleID"].ToStr();
        public  bool EnabledPermission = ConfigurationManager.AppSettings["EnabledPermission"].ToBool();
        public SystemService(IUserRepository userRepository,IMenuRepository menuRepository,IUnitOfWork unitOfWork)
        {
            this.userRepository = userRepository;
            this.menuRepository = menuRepository;
            this.unitOfWork = unitOfWork;
        }
        /// <summary>
        /// 判断指定用户是否管理员
        /// </summary>
        /// <param name="UserID"></param>
        /// <returns></returns>
        public bool IsAdministrator(string UserID)
        {
            if (UserID == AdminUserID && AdminUserID != "")
                return true;
            //如果没有配置管理员角色
            if (AdminRoleID == "") return false;

            //如果用户角色包括AdminRoleID
            return userRepository.Get(UserID).Roles.Where(r => r.RoleID == AdminRoleID).Any();
        }
        /// <summary>
        /// 判断当前用户是否是管理员
        /// </summary>
        /// <returns></returns>
        public bool IsAdministrator()
        {
            if (SysContext.CurrentUserID == AdminUserID && AdminUserID != "") return true;
            //如果没有配置管理员角色
            if (AdminRoleID == "") return false;
            if (SysContext.CurrentRoleID.ToStr() == AdminRoleID) return true;
            var roleids = SysContext.CurrentRoleID.Split(',');
            if (roleids.Contains(AdminRoleID.ToStr())) return true;
            return false;
        }
        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public  bool UserLogin(string username, string password)
        {
            var loginSuccess = userRepository.GetAll().Where(u => u.LoginName == username && u.LoginPassword == password).Any();
            if (loginSuccess)
            {
                var user = userRepository.GetAll().Where(u => u.LoginName == username && u.LoginPassword == password).First();
                var roles = userRepository.GetAll().Where(u => u.UserID == user.UserID).First().Roles.ToList();
                var roleids = Array.ConvertAll<string, string>(roles.Select(c => c.RoleID).ToArray(), c => c.ToStr());
                SysContext.CurrentUserID = user.UserID;
                if (string.IsNullOrEmpty( user.DeptID))
                    SysContext.CurrentDeptID = user.DeptID.ToStr();
                if (string.IsNullOrEmpty(user.EmployeeID))
                    SysContext.CurrentEmployeeID = user.EmployeeID.ToStr();
                if (string.IsNullOrEmpty(user.SupplierID))
                    SysContext.CurrentSupplierID = user.SupplierID.ToStr();
                if (user.LastLoginTime.HasValue)
                    SysContext.CurrentUserLastLoginTime = user.LastLoginTime.Value.ToStr();

                SysContext.CurrentUserTitle = user.Title;

                LogManager.WriteLog("User", user.Title + "登陆系统");

                user.LastLoginTime = DateTime.Now;
                Random rnd = new Random(Environment.TickCount);
                user.SID = rnd.Next(100000, 999999).ToString();
                userRepository.Update(user);
                unitOfWork.Commit();

                SysContext.CurrentRoleID = string.Join(",", roleids);       
            }
            return loginSuccess;
        }
        
        public List<Sys_Menu> GetUserMenus(string UserID)
        {
            if (!EnabledPermission || IsAdministrator(UserID))
                return menuRepository.GetAll().ToList();
            var sql=GetUserMenusCommandText(UserID);
            List<Sys_Menu> menus=unitOfWork.GetZeroContext().Database.SqlQuery<Sys_Menu>(sql).ToList();

            return menus;
           
        }


        public string GetUserMenusCommandText(string UserID)
        {
            string sql = @" select * from sys_menu where (menuid in({0}) or menuid in({1})) and menuid not in ({2}) ";

            //子查询1：获取用户有权限的菜单ID
            string query1 = @"select distinct PrivilegeAccessKey from CF_Privilege where PrivilegeMaster = 'CF_User' and PrivilegeMasterKey = '{0}' and PrivilegeAccess = 'Sys_Menu' and PrivilegeOperation = 'Permit'".FormatWith(UserID);
            //子查询2：获取用户所属角色有权限的菜单ID
            string query2 = @"select distinct PrivilegeAccessKey from CF_Privilege where PrivilegeMaster = 'CF_Role' and PrivilegeMasterKey in (select CF_Role_RoleID from CF_UserCF_Role where CF_User_UserID = '{0}') and PrivilegeAccess = 'Sys_Menu' and PrivilegeOperation = 'Permit'".FormatWith(UserID);
            //子查询3：获取用户禁止权限的菜单ID
            string query3 = @"select distinct PrivilegeAccessKey from CF_Privilege where PrivilegeMaster = 'CF_User' and PrivilegeMasterKey = '{0}' and PrivilegeAccess = 'Sys_Menu' and PrivilegeOperation = 'Forbid'".FormatWith(UserID);

            sql = sql.FormatWith(query1, query2, query3);

            return sql;
        }
        
    }
    public interface ISystemService 
    {
        bool UserLogin(string username, string password);
        bool IsAdministrator(string UserID);
        bool IsAdministrator();
        List<Sys_Menu> GetUserMenus(string UserID);
    }
}
